﻿Imports System.Data
Imports Sistema_InformacionNaviera.BC
Imports Sistema_InformacionNaviera.BE
Imports Sistema_InformacionNavier.UTIL


Public Class BillOfLadingExpo

    Inherits PaginaBase
    Dim i_KVJE As Integer   'Codigo de la nave/ viaje
    Dim i_KBLM As Integer ' correlativo de importacion

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then

            Session("FlagBL") = 1 ' si es exportacion  

            CargarTipoBulto("TB")
            CargarTipoBultoMercaderia("TBM")
            CargarAgenteAduana("AA")
            CargarAgenteDocumetario("AD")
            'CargarLinea("LN")
            CargarLinea()
            CargarServicio("SR")
            btnCancelar.Enabled = False

            CrearTablaTemporalFlete()
            CrearTablaTemporalContenedor()
            CrearTablaMercaderia()

            sTab.ActiveTabIndex = 0

            If Session("TipoTransaccionBLImpo") = 0 Then  ' Nuevo 

                lblTitulo.Text = "Nuevo Bill of Lading Exportación"
                'CrearTablaTemporalFlete()
                'CrearTablaTemporalContenedor()
                'CrearTablaMercaderia()
                txtCodNave.Text = Session("CodNaveViajeBLImpo")
                txtDesNave.Text = Session("DesNaveViajeBLImpo")


            ElseIf Session("TipoTransaccionBLImpo") = 1 Then  ' Modifica 

                lblTitulo.Text = "Modificar Bill of Lading Exportación"
                'CrearTablaTemporalFlete()
                'CrearTablaTemporalContenedor()
                'CrearTablaMercaderia()
                CargarDatosBlImpo()
                'Nuevo()
            End If

        End If

        '-----------------------------------------------------------------------

        '-----------------------------------------------------------------------
        If My.Request.Params("__EVENTTARGET") = "MiFuncionPaquetes" Then

            If Session("BSSCodigoEntidadEMB") = Nothing Then
                txtCodEmbarcador.Text = String.Empty
            Else
                txtCodEmbarcador.Text = Session("BSSCodigoEntidadEMB")
                txtDesEmbarcador.Text = Session("BSSNombreEntidadEMB")

            End If


            If Session("BSSCodigoEntidadCON") = Nothing Then
                txtCodConsig.Text = String.Empty
            Else
                txtCodConsig.Text = Session("BSSCodigoEntidadCON")
                txtDesConsig.Text = Session("BSSNombreEntidadCON")

            End If


            If Session("BSSCodigoEntidadNOT") = Nothing Then
                txtCodNotificante.Text = String.Empty
            Else
                txtCodNotificante.Text = Session("BSSCodigoEntidadNOT")
                txtDesNotificante.Text = Session("BSSNombreEntidadNOT")

            End If


        End If


        If My.Request.Params("__EVENTTARGET") = "MiFuncionTarifa" Then
            If Session("BPCodTarifa") = Nothing Then
                txtTarifaFlete.Text = String.Empty
            Else
                txtTarifaFlete.Text = Session("BPCodTarifa")
                txtDesTarifaFlete.Text = Session("BPDesTarifa")

            End If
        End If


        If My.Request.Params("__EVENTTARGET") = "MiFuncionPuertos1" Then
            If Session("BPCodPuerto") = Nothing Then
                txtPtoOrigen.Text = String.Empty
            Else
                txtPtoOrigen.Text = Session("BPCodPuerto")
                txtDesPtoOrigen.Text = Session("BPDesPuerto")

            End If
        End If

        If My.Request.Params("__EVENTTARGET") = "MiFuncionPuertos2" Then
            If Session("BPCodPuerto") = Nothing Then
                txtPtoEmb.Text = String.Empty
            Else
                txtPtoEmb.Text = Session("BPCodPuerto")
                txtDesPtoEmb.Text = Session("BPDesPuerto")

            End If
        End If

        If My.Request.Params("__EVENTTARGET") = "MiFuncionPuertos3" Then
            If Session("BPCodPuerto") = Nothing Then
                txtPtoDesc.Text = String.Empty
            Else
                txtPtoDesc.Text = Session("BPCodPuerto")
                txtDesPtoDesc.Text = Session("BPDesPuerto")

            End If
        End If

        If My.Request.Params("__EVENTTARGET") = "MiFuncionPuertos4" Then
            If Session("BPCodPuerto") = Nothing Then
                txtPtoFinal.Text = String.Empty
            Else
                txtPtoFinal.Text = Session("BPCodPuerto")
                txtDesDestinoFinal.Text = Session("BPDesPuerto")

            End If
        End If


    End Sub

    Protected Sub btnGrabar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGrabar.Click
        Try

            Dim sUsuario As String = Session("idIusuario")
            Dim objBLImpoBE As BillOfLadingImpoBE

            If Session("TipoTransaccionBLImpo") = 1 Then ' Modificar
                objBLImpoBE = New BillOfLadingImpoBE
                objBLImpoBE.Umod = sUsuario
                Modificar()
            Else
                objBLImpoBE = New BillOfLadingImpoBE
                objBLImpoBE.Ucre = sUsuario
                Nuevo()
            End If

        Catch ex As Exception
            ex.Message.ToString()
        End Try
    End Sub



    Public Sub Nuevo()

        Try

            Dim dtMercaderia As New DataTable
            Dim dtFlete As New DataTable
            Dim dtContenedor As New DataTable

            Dim TOPE As String

            If txtBL.Text = String.Empty Then
                MsgBox("Ingrese el número de BL.", True, String.Empty)
                Exit Sub
            ElseIf txtFechaEmision.Text.Trim = "" Then
                MsgBox("Ingrese la fecha de emision.", True, String.Empty)
                Exit Sub
            End If

            '--------------------------------------------------------------------------------------------------------
            ' Validacion del detalle
            '--------------------------------------------------------------------------------------------------------

            dtMercaderia = Session("tbTempMercaderia")
            dtFlete = Session("tbTempFlete")
            dtContenedor = Session("tbTempContenedor")

            If dtMercaderia.Rows.Count = 0 Then
                MsgBox("ERROR: Debe ingresar la mercaderia.", True, String.Empty)
                Exit Sub
            End If

            If dtFlete.Rows.Count = 0 Then
                MsgBox("ERROR: Debe ingresar el flete.", True, String.Empty)
                Exit Sub
            End If

            If dtContenedor.Rows.Count = 0 Then
                MsgBox("ERROR: Debe ingresar el contenedor.", True, String.Empty)
                Exit Sub
            End If

            '--------------------------------------------------------------------------------------------------------
            ' Ingresar BL Impo
            '--------------------------------------------------------------------------------------------------------

            Dim objBLImpoBE As BillOfLadingImpoBE
            Dim objBLImpoBC As BillOfLadingImpoBC
            Dim bExito As Boolean = False
            Dim sMensaje As String = String.Empty
            Dim sUsuario As String = Session("idIusuario")


            Dim KVJE As Integer = txtCodNave.Text.Trim   'Codigo de la nave/ viaje
            Dim KBLM As Integer = 0 ' correlativo de importacion

            If Session("TipoTransaccionBLImpo") = 1 Then
                TOPE = "M" ' 
            Else
                TOPE = "N" ' Tipo de Ingeso = Nuevo
            End If

            Dim sTipo As String = "I"
            Dim Nume As String = txtBL.Text.Trim
            Dim Tibl As String = cboUnidadPeso.SelectedValue
            Dim Lemi As String = txtLugarEmision.Text
            Dim Femi As String = txtFechaEmision.Text.Trim
            Dim Emba As String = txtCodEmbarcador.Text.Trim
            Dim Csne As String = txtCodConsig.Text.Trim
            Dim Noti As String = txtCodNotificante.Text.Trim
            Dim Not2 As String = ""
            Dim Fwdr As String = "" 'Razón Social Forwarder
            Dim Agad As String = txtAgenteAduana.Text
            Dim Line As String = cboLinea.SelectedValue
            Dim Ptoo As String = txtPtoOrigen.Text.Trim
            Dim Ptoe As String = txtPtoEmb.Text.Trim
            Dim Dfin As String = txtPtoFinal.Text.Trim
            Dim Dfi2 As String = txtPtoDesc.Text.Trim
            Dim Dpte As String = txtDesPtoEmb.Text.Trim  ' Descripción del puerto de embarque
            Dim Dpto As String = txtDesPtoOrigen.Text.Trim  ' Descripción del puerto de origen
            Dim Dptd As String = txtDesPtoDesc.Text.Trim  'Descripción del puerto de descarga
            Dim Ddfi As String = txtDesDestinoFinal.Text.Trim
            Dim Ddf2 As String = "" ' Descripción del destion final 2 (por responsabilidad del embarcador)
            Dim Fomt As String = cboFull.SelectedValue  ' Indicador BL lleno o vacío (F: Full E: Empty) 
            Dim OBSE As String = ""
            Dim Tfpf As Double = 0 'Total Freight Prepaid – Fletes menos THC (Uso comercial)
            Dim Tfpt As Double = 0 'Total Freight Prepaid – THC (Uso comercial)
            Dim Tfcf As Double = 0 ' Total Freight Collect – Fletes menos THC (Uso comercial)
            Dim Tfct As Double = 0 ' Total Freight Collect – THC (Uso comercial)
            Dim CFLE As String = "" 'Condición del Flete (A:Amortizado  C:Cancelado  P:Pendiente)
            Dim Unid As Integer = Val(txtCantMercaderia.Text.Trim) 'Cantidad de unidades (NULL la nave/viaje es tipo carros) 
            Dim Csue As Integer = 0 ' Total peso carga suelta (NULL la nave/viaje es tipo granelero o carros)
            Dim Pkgs As Integer = 0 ' Total paquetes (NULL la nave/viaje es tipo granelero o carros)
            Dim Tafle As Double = 0 ' Total amortización Fletes menos THC
            Dim Tathc As Double = 0 ' Total amortización de THC
            Dim ESTA As Integer = 0 ' Flag Estado (0: Activo, 1:Anulado)
            Dim Agge As String = cboAgenteAduana.SelectedValue ' Código agente general
            Dim Serv As String = cboServ.SelectedValue ' Código Servicio
            Dim Norig As Integer = Val(txtNumeroOrigen.Text.Trim)  ' Número de Bls originales
            Dim Dtot As String = "" 'Descripción de totales de contenedores o paquetes (en texto)
            Dim Lpfp As String = "" ' Lugar pago de flete prepaid
            Dim Lpfc As String = "" ' Lugar pago de flete collect
            Dim Talm As String = "" ' Tipo de almacén
            Dim Agdo As String = cboDocumentario.SelectedValue  ' Código agente documentario
            Dim Tdes As String = "" ' Tipo de descarga (D: Directa N:Normal)
            Dim Cond As String = "" ' Condición del contenedor (HH, HP, PP, PH, EM)
            Dim OpeLog As String = txtOperadorLogis.Text.Trim  ' Código Operador logístico
            Dim CUSU As String = sUsuario ' usuario logueado - falta
            Dim TfcfInt As Double = 0 'Total Flete collect Interno
            Dim TfctInt As Double = 0 ' Total THC Interno
            Dim Ptod As String = txtPtoDesc.Text.Trim  ' Código de Puerto de descarga

            Dim sEnt_ObsEmb As String = txtObsEmbarcador.Text.Trim
            Dim sEnt_ObsCons As String = txtObsConsig.Text.Trim
            Dim sEnt_ObsDoc As String = txtObsNotificante.Text.Trim

            objBLImpoBE = New BillOfLadingImpoBE
            objBLImpoBE.Tipo = sTipo
            objBLImpoBE.KVJE = KVJE
            objBLImpoBE.KBLM = KBLM

            '------------------------------------------------
            ' si se va a modificar
            '------------------------------------------------
            If Session("TipoTransaccionBLImpo") = 1 Then
                objBLImpoBE.TOPE = "M"
                objBLImpoBE.KBLM = Session("CodigBL")
                objBLImpoBE.KVJE = Session("CodigVje")

            End If
            '------------------------------------------------

            objBLImpoBE.TOPE = TOPE
            objBLImpoBE.Nume = Nume
            objBLImpoBE.Tibl = Tibl
            objBLImpoBE.Lemi = Lemi
            objBLImpoBE.Femi = Femi
            objBLImpoBE.Emba = Emba
            objBLImpoBE.Csne = Csne
            objBLImpoBE.Noti = Noti
            objBLImpoBE.Not2 = Not2
            objBLImpoBE.Fwdr = Fwdr
            objBLImpoBE.Agad = Agad
            objBLImpoBE.Line = Line
            objBLImpoBE.Ptoo = Ptoo
            objBLImpoBE.Ptoe = Ptoe
            objBLImpoBE.Dfin = Dfin
            objBLImpoBE.Dfi2 = Dfi2
            objBLImpoBE.Dpte = Dpte
            objBLImpoBE.Dpto = Dpto
            objBLImpoBE.Dptd = Dptd
            objBLImpoBE.Ddfi = Ddfi
            objBLImpoBE.Ddf2 = Ddf2
            objBLImpoBE.Fomt = Fomt
            objBLImpoBE.OBSE = OBSE
            objBLImpoBE.Tfpf = Tfpf
            objBLImpoBE.Tfpt = Tfpt
            objBLImpoBE.Tfcf = Tfcf
            objBLImpoBE.Tfct = Tfct
            objBLImpoBE.CFLE = CFLE
            objBLImpoBE.Unid = Unid
            objBLImpoBE.Csue = Csue
            objBLImpoBE.Pkgs = Pkgs
            objBLImpoBE.Tafle = Tafle
            objBLImpoBE.Tathc = Tathc
            objBLImpoBE.ESTA = ESTA
            objBLImpoBE.Agge = Agge
            objBLImpoBE.Serv = Serv
            objBLImpoBE.Norig = Norig
            objBLImpoBE.Dtot = Dtot
            objBLImpoBE.Lpfp = Lpfp
            objBLImpoBE.Lpfc = Lpfc
            objBLImpoBE.Talm = Talm
            objBLImpoBE.Agdo = Agdo
            objBLImpoBE.Tdes = Tdes
            objBLImpoBE.Cond = Cond
            objBLImpoBE.OpeLog = OpeLog
            objBLImpoBE.CUSU = CUSU
            objBLImpoBE.TfcfInt = TfcfInt
            objBLImpoBE.TfctInt = TfctInt
            objBLImpoBE.Ptod = Ptod
            objBLImpoBE.Ent_ObsEmb = sEnt_ObsEmb
            objBLImpoBE.Ent_ObsCons = sEnt_ObsCons
            objBLImpoBE.Ent_ObsDoc = sEnt_ObsDoc
            objBLImpoBE.Bli_Flag = Session("FlagBL")


            objBLImpoBC = New BillOfLadingImpoBC


            objBLImpoBC.InsertarBLImpo(objBLImpoBE, bExito, sMensaje)
            '------------------------------------------------------------------

            If bExito = False Then
                MsgBox("Error: Hubieron problemas al ingresar el Bl Importacion.", True, String.Empty)
                Exit Sub
            Else


                '------------------------------------------------------------------
                'obtener codigo correlativo
                '------------------------------------------------------------------
                If Session("TipoTransaccionBLImpo") = 0 Then
                    'objBLImpoBC = New BillOfLadingImpoBC
                    objBLImpoBC.ObtieneBlImpo_CodMax(objBLImpoBE, i_KBLM)
                    objBLImpoBE.KBLM = i_KBLM

                End If
                '------------------------------------------------------------------

                Dim bResultadoCont As Boolean
                Dim bResultadoFlete As Boolean
                Dim bResultadoMercaderia As Boolean

                InsertarBL_Contenedores(bResultadoCont)
                If bResultadoCont = True Then

                    InsertarBL_Flete(bResultadoFlete)

                    If bResultadoFlete = True Then
                        InsertarBL_Mercaderia(bResultadoMercaderia)
                        If bResultadoMercaderia = True Then
                            MsgBox("EXITO: Los datos fueron grabados correctamente.", True, String.Empty)
                            LimpiarControles()
                            Response.Redirect("Consultar_BillOfLading_Expo.aspx")
                        End If
                    End If


                End If



            End If


            '--------------------------------------------------------------------------------------------------------


        Catch ex As Exception
            ex.Message.ToString()
        End Try


    End Sub

    Public Sub InsertarBL_Mercaderia(ByRef bResultado As Boolean)
        Try

            Dim dtMercaderia As New DataTable
            dtMercaderia = Session("tbTempMercaderia")


            Dim objBLImpoBE As BillOfLadingImpoBE
            Dim objBLImpoBC As BillOfLadingImpoBC
            Dim bExito As Boolean = False
            Dim sMensaje As String = String.Empty
            Dim i As Integer
            Dim drItem As DataRow

            If dtMercaderia.Rows.Count > 0 Then
                Do While i < dtMercaderia.Rows.Count
                    drItem = dtMercaderia.Rows(i)

                    Dim KVJE As Integer = txtCodNave.Text.Trim   'Codigo de la nave/ viaje
                    Dim iItem As Integer = CType(drItem.Item("IDMercaderia").ToString, Integer)
                    Dim sDescMerc As String = CType(drItem.Item("DescMercaderia").ToString, String)
                    Dim sEstado As String = CType(drItem.Item("dMercaderiaEstado").ToString, String)
                    Dim sProd As String = cboProducto.SelectedValue
                    Dim sTipoBulto As String = cboTipoBulto.SelectedValue
                    Dim sCant As String = txtCantMercaderia.Text.Trim
                    Dim sParAran As String = txtPartida.Text.Trim
                    Dim sPesoBruto As String = txtPesoBrutoMer.Text.Trim
                    Dim sTotal As String = txtTotalMer.Text.Trim
                    Dim sVolumen As String = txtVolumen.Text.Trim
                    Dim sMarcaNum As String = txtMarcas.Text.Trim

                    Dim CUSU As String = Session("idIusuario")


                    objBLImpoBE = New BillOfLadingImpoBE
                    objBLImpoBE.TOPE = "N"
                    objBLImpoBE.Tipo = "I"
                    objBLImpoBE.KVJE = KVJE
                    objBLImpoBE.KBLM = i_KBLM





                    '------------------------------------------------
                    ' si se va a modificar
                    '------------------------------------------------
                    If Session("TipoTransaccionBLImpo") = 1 Then
                        objBLImpoBE.TOPE = "M"
                        objBLImpoBE.KBLM = Session("CodigBL")
                        objBLImpoBE.KVJE = Session("CodigVje")

                        If CType(drItem.Item("dMercaderiaEstado").ToString, String) = "0" Then
                            objBLImpoBE.TOPE = "N"
                            objBLImpoBE.KBLM = Session("CodigBL")
                            objBLImpoBE.KVJE = Session("CodigVje")
                        End If

                    End If
                    '------------------------------------------------



                    objBLImpoBE.Bef_Item = iItem
                    objBLImpoBE.Bef_Desc = sDescMerc
                    objBLImpoBE.Bem_Prod = sProd
                    objBLImpoBE.Bem_TipoBulto = sTipoBulto
                    objBLImpoBE.Bem_Cant = sCant
                    objBLImpoBE.Bem_ParAran = sParAran
                    objBLImpoBE.Bem_PesoBruto = sPesoBruto
                    objBLImpoBE.Bem_Total = sTotal
                    objBLImpoBE.Bem_Volumen = sVolumen
                    objBLImpoBE.Bem_MarcaNum = sMarcaNum
                    objBLImpoBE.Bem_Est = sEstado
                    objBLImpoBE.Ucre = CUSU
                    objBLImpoBE.Umod = CUSU

                    objBLImpoBC = New BillOfLadingImpoBC
                    objBLImpoBC.InsertarBLImpoMercaderia(objBLImpoBE, bExito, sMensaje)

                    i = i + 1
                Loop
            End If

            If bExito = False Then
                MsgBox("Error: Hubieron problemas al ingresar el Bl Importacion.", True, String.Empty)
                Exit Sub
            Else
                bResultado = bExito ' es OK
            End If


        Catch ex As Exception
            ex.Message.ToString()
        End Try

    End Sub


    Public Sub InsertarBL_Contenedores(ByRef bResultado As Boolean)
        Try
            'Dim dtFlete As New DataTable
            Dim dtContenedor As New DataTable

            'dtFlete = Session("tbTempFlete")
            dtContenedor = Session("tbTempContenedor")

            Dim objBLImpoBE As BillOfLadingImpoBE
            Dim objBLImpoBC As BillOfLadingImpoBC
            Dim bExito As Boolean = False
            Dim sMensaje As String = String.Empty
            Dim i As Integer
            Dim drItem As DataRow

            If dtContenedor.Rows.Count > 0 Then
                Do While i < dtContenedor.Rows.Count
                    drItem = dtContenedor.Rows(i)

                    Dim sBec_Pref As String = CType(drItem.Item("sPrefijo").ToString, String)
                    Dim sBec_nume As String = CType(drItem.Item("sNumero").ToString, String)
                    Dim sBec_Tipo As String = CType(drItem.Item("sTipo").ToString, String)
                    Dim iBec_Pies As Integer = CType(drItem.Item("iPies").ToString, Integer)
                    Dim sBec_Dpto As String = "" 'CType(drItem.Item("").ToString, String) Descripción del operador del terminal
                    Dim dBec_Volu As Double = CType(drItem.Item("sVolumenContenedor").ToString, Double)
                    Dim dBec_Tara As Double = CType(drItem.Item("sTara").ToString, Double)
                    Dim dBec_Cond As String = CType(drItem.Item("sCondicion").ToString, String)
                    Dim sBec_Temp As String = CType(drItem.Item("sTemp").ToString, String)
                    Dim sBec_Imo As String = "" 'CType(drItem.Item("").ToString, String) 'Indice de peligrosidad
                    Dim sBec_Unno As String = CType(drItem.Item("sUNNO").ToString, String)
                    Dim sBec_Talm As String = "" ' CType(drItem.Item("").ToString, String) 'Tipo de almacenamiento
                    Dim sBec_EstaTrans As String = CType(drItem.Item("sEstadoTrans").ToString, String)
                    Dim sBec_Esta As String = CType(drItem.Item("dContenedorEstado").ToString, String)

                    Dim sBec_LineIni As String = CType(drItem.Item("sLineaInicial").ToString, String)
                    Dim sBec_LineStock As String = CType(drItem.Item("sLineaStock").ToString, String)
                    Dim sBec_TipoPaq As String = CType(drItem.Item("sTipoPaquete").ToString, String)
                    Dim iBec_Cantidad As Integer = CType(drItem.Item("iCantidad").ToString, Integer)
                    Dim sBec_Unid As String = CType(drItem.Item("sUnidadMedida").ToString, String)
                    Dim dBec_PesoBruto As Double = CType(drItem.Item("dPesoBrutoCont").ToString, Double)
                    Dim dBec_PesoNeto As Double = CType(drItem.Item("dPesoNeto").ToString, String)
                    Dim sBec_Carrier As String = CType(drItem.Item("sCarrier").ToString, String)
                    Dim sBec_Shipper As String = CType(drItem.Item("sShipper").ToString, String)
                    Dim sBec_Obs As String = CType(drItem.Item("sObservaciones").ToString, String)
                    Dim CUSU As String = Session("idIusuario")


                    Dim KVJE As Integer = txtCodNave.Text.Trim   'Codigo de la nave/ viaje

                    objBLImpoBE = New BillOfLadingImpoBE
                    objBLImpoBE.TOPE = "N"
                    objBLImpoBE.Tipo = "I"
                    objBLImpoBE.KVJE = KVJE
                    objBLImpoBE.KBLM = i_KBLM

                    '------------------------------------------------
                    ' si se va a modificar
                    '------------------------------------------------
                    If Session("TipoTransaccionBLImpo") = 1 Then
                        objBLImpoBE.TOPE = "M"
                        objBLImpoBE.KBLM = Session("CodigBL")
                        objBLImpoBE.KVJE = Session("CodigVje")

                        If CType(drItem.Item("dContenedorEstado").ToString, String) = "0" Then
                            objBLImpoBE.TOPE = "N"
                            objBLImpoBE.KBLM = Session("CodigBL")
                            objBLImpoBE.KVJE = Session("CodigVje")
                        End If

                    End If
                    '------------------------------------------------

                    objBLImpoBE.Bec_Pref = sBec_Pref
                    objBLImpoBE.Bec_nume = sBec_nume
                    objBLImpoBE.Bec_Tipo = sBec_Tipo
                    objBLImpoBE.Bec_Pies = iBec_Pies
                    objBLImpoBE.Bec_Dpto = sBec_Dpto
                    objBLImpoBE.Bec_Volu = dBec_Volu
                    objBLImpoBE.Bec_Tara = dBec_Tara
                    objBLImpoBE.Bec_Cond = dBec_Cond
                    objBLImpoBE.Bec_Temp = sBec_Temp
                    objBLImpoBE.Bec_Imo = sBec_Imo
                    objBLImpoBE.Bec_Unno = sBec_Unno
                    objBLImpoBE.Bec_Talm = sBec_Talm
                    objBLImpoBE.Bec_Esta = sBec_Esta
                    objBLImpoBE.Bec_EstaTrans = sBec_EstaTrans
                    objBLImpoBE.Bec_LineIni = sBec_LineIni
                    objBLImpoBE.Bec_LineStock = sBec_LineStock
                    objBLImpoBE.Bec_TipoPaq = sBec_TipoPaq
                    objBLImpoBE.Bec_Cantidad = iBec_Cantidad
                    objBLImpoBE.Bec_Unid = sBec_Unid
                    objBLImpoBE.Bec_PesoBruto = dBec_PesoBruto
                    objBLImpoBE.Bec_PesoNeto = dBec_PesoNeto
                    objBLImpoBE.Bec_Carrier = sBec_Carrier
                    objBLImpoBE.Bec_Shipper = sBec_Shipper
                    objBLImpoBE.Bec_Obs = sBec_Obs
                    objBLImpoBE.Ucre = CUSU

                    objBLImpoBC = New BillOfLadingImpoBC
                    objBLImpoBC.InsertarBLImpoContenedores(objBLImpoBE, bExito, sMensaje)

                    i = i + 1
                Loop
            End If

            If bExito = False Then
                MsgBox("Error: Hubieron problemas al ingresar el Bl Importacion.", True, String.Empty)
                Exit Sub
            Else
                bResultado = bExito ' es OK
            End If


        Catch ex As Exception
            ex.Message.ToString()
        End Try

    End Sub

    Public Sub InsertarBL_Flete(ByRef bResultado As Boolean)
        Try

            Dim dtFlete As New DataTable
            dtFlete = Session("tbTempFlete")

            Dim objBLImpoBE As BillOfLadingImpoBE
            Dim objBLImpoBC As BillOfLadingImpoBC
            Dim bExito As Boolean = False
            Dim sMensaje As String = String.Empty
            Dim i As Integer
            Dim drItem As DataRow

            Dim CUSU As String = Session("idIusuario")

            If dtFlete.Rows.Count > 0 Then
                Do While i < dtFlete.Rows.Count
                    drItem = dtFlete.Rows(i)
                    Dim iBef_Kfle As String = CType(drItem.Item("dFleteID").ToString, String)
                    Dim sBef_Tari As String = CType(drItem.Item("dFleteTarifa").ToString, String)
                    Dim sBef_Umed As String = CType(drItem.Item("sFleteUnidad").ToString, String)
                    Dim dBef_Cant As String = CType(drItem.Item("iFleteCantidad").ToString, String)
                    Dim dBef_Tfle As Integer = CType(drItem.Item("dFleteMontoTarifa").ToString, Integer)
                    Dim dBef_Tmon As Double = CType(drItem.Item("dFleteTotal").ToString, Double)
                    Dim sBef_Tpag As String = ""
                    Dim sBef_Mone As String = CType(drItem.Item("sFleteMoneda").ToString, String)
                    Dim sBef_Dfle As String = ""
                    Dim sBef_Lpag As String = CType(drItem.Item("sFleteLugarPago").ToString, String)
                    Dim sBef_PC As String = CType(drItem.Item("dFletePC").ToString, String)
                    Dim sBef_Est As String = CType(drItem.Item("dFleteEstado").ToString, String)
                    Dim KVJE As Integer = txtCodNave.Text.Trim   'Codigo de la nave/ viaje

                    objBLImpoBE = New BillOfLadingImpoBE
                    objBLImpoBE.TOPE = "N"
                    objBLImpoBE.Tipo = "I"
                    objBLImpoBE.KVJE = KVJE
                    objBLImpoBE.KBLM = i_KBLM

                    '------------------------------------------------
                    ' si se va a modificar
                    '------------------------------------------------
                    If Session("TipoTransaccionBLImpo") = 1 Then
                        objBLImpoBE.TOPE = "M"
                        objBLImpoBE.KBLM = Session("CodigBL")
                        objBLImpoBE.KVJE = Session("CodigVje")

                        If CType(drItem.Item("dFleteEstado").ToString, String) = "0" Then
                            objBLImpoBE.TOPE = "N"
                            objBLImpoBE.KBLM = Session("CodigBL")
                            objBLImpoBE.KVJE = Session("CodigVje")
                        End If

                    End If
                    '------------------------------------------------

                    objBLImpoBE.Bef_Kfle = iBef_Kfle
                    objBLImpoBE.Bef_Tari = sBef_Tari
                    objBLImpoBE.Bef_Umed = sBef_Umed
                    objBLImpoBE.Bef_Cant = dBef_Cant
                    objBLImpoBE.Bef_Tfle = dBef_Tfle
                    objBLImpoBE.Bef_Tmon = dBef_Tmon
                    objBLImpoBE.Bef_Tpag = sBef_Tpag
                    objBLImpoBE.Bef_Mone = sBef_Mone
                    objBLImpoBE.Bef_Tpag = sBef_Tpag
                    objBLImpoBE.Bef_Mone = sBef_Mone
                    objBLImpoBE.Bef_Dfle = sBef_Dfle
                    objBLImpoBE.Bef_Lpag = sBef_Lpag
                    objBLImpoBE.Ucre = CUSU
                    objBLImpoBE.Umod = CUSU
                    objBLImpoBE.Bef_PC = sBef_PC
                    objBLImpoBE.Bec_Esta = sBef_Est


                    objBLImpoBC = New BillOfLadingImpoBC
                    objBLImpoBC.InsertarBLImpoFletes(objBLImpoBE, bExito, sMensaje)

                    i = i + 1
                Loop
            End If

            If bExito = False Then
                MsgBox("Error: Hubieron problemas al ingresar el Bl Importacion.", True, String.Empty)
                Exit Sub
            Else
                bResultado = bExito ' es OK
            End If

        Catch ex As Exception
            ex.Message.ToString()
        End Try

    End Sub

    Public Sub Modificar()

        Try
            'ModificarCabecera()
            Nuevo()
        Catch ex As Exception
            ex.Message.ToString()
        End Try
    End Sub

    Public Sub ModificarCabecera()

        Try
            Dim objUtil As New Funciones
            Dim objBLImpoBE As BillOfLadingImpoBE
            Dim objBLImpoBC As BillOfLadingImpoBC

            Dim bExito As Boolean = False
            Dim sMensaje As String = String.Empty

            Dim sUsuario As String = Session("idIusuario")

            Dim KVJE As Integer = txtCodNave.Text.Trim   'Codigo de la nave/ viaje
            Dim KBLM As Integer = 0 ' correlativo de importacion
            Dim TOPE As String = "M" ' Tipo de Ingeso = Nuevo
            Dim sTipo As String = "I"
            Dim Nume As String = txtBL.Text.Trim
            Dim Tibl As String = cboUnidadPeso.SelectedValue
            Dim Lemi As String = txtLugarEmision.Text
            Dim Femi As String = txtFechaEmision.Text.Trim
            Dim Emba As String = txtCodEmbarcador.Text.Trim
            Dim Csne As String = txtCodConsig.Text.Trim
            Dim Noti As String = txtCodNotificante.Text.Trim
            Dim Not2 As String = ""
            Dim Fwdr As String = "" 'Razón Social Forwarder
            Dim Agad As String = txtAgenteAduana.Text
            Dim Line As String = cboLinea.SelectedValue
            Dim Ptoo As String = txtPtoOrigen.Text.Trim
            Dim Ptoe As String = txtPtoEmb.Text.Trim
            Dim Dfin As String = txtPtoFinal.Text.Trim
            Dim Dfi2 As String = txtPtoDesc.Text.Trim
            Dim Dpte As String = txtDesPtoEmb.Text.Trim  ' Descripción del puerto de embarque
            Dim Dpto As String = txtDesPtoOrigen.Text.Trim  ' Descripción del puerto de origen
            Dim Dptd As String = txtDesPtoDesc.Text.Trim  'Descripción del puerto de descarga
            Dim Ddfi As String = txtDesDestinoFinal.Text.Trim
            Dim Ddf2 As String = "" ' Descripción del destion final 2 (por responsabilidad del embarcador)
            Dim Fomt As String = cboFull.SelectedValue  ' Indicador BL lleno o vacío (F: Full E: Empty) 
            Dim OBSE As String = ""
            Dim Tfpf As Double = 0 'Total Freight Prepaid – Fletes menos THC (Uso comercial)
            Dim Tfpt As Double = 0 'Total Freight Prepaid – THC (Uso comercial)
            Dim Tfcf As Double = 0 ' Total Freight Collect – Fletes menos THC (Uso comercial)
            Dim Tfct As Double = 0 ' Total Freight Collect – THC (Uso comercial)
            Dim CFLE As String = "" 'Condición del Flete (A:Amortizado  C:Cancelado  P:Pendiente)
            Dim Unid As Integer = Val(txtCantMercaderia.Text.Trim) 'Cantidad de unidades (NULL la nave/viaje es tipo carros) 
            Dim Csue As Integer = 0 ' Total peso carga suelta (NULL la nave/viaje es tipo granelero o carros)
            Dim Pkgs As Integer = 0 ' Total paquetes (NULL la nave/viaje es tipo granelero o carros)
            Dim Tafle As Double = 0 ' Total amortización Fletes menos THC
            Dim Tathc As Double = 0 ' Total amortización de THC
            Dim ESTA As Integer = 0 ' Flag Estado (0: Activo, 1:Anulado)
            Dim Agge As String = cboAgenteAduana.SelectedValue ' Código agente general
            Dim Serv As String = cboServ.SelectedValue ' Código Servicio
            Dim Norig As Integer = Val(txtNumeroOrigen.Text.Trim)  ' Número de Bls originales
            Dim Dtot As String = "" 'Descripción de totales de contenedores o paquetes (en texto)
            Dim Lpfp As String = "" ' Lugar pago de flete prepaid
            Dim Lpfc As String = "" ' Lugar pago de flete collect
            Dim Talm As String = "" ' Tipo de almacén
            Dim Agdo As String = cboDocumentario.SelectedValue  ' Código agente documentario
            Dim Tdes As String = "" ' Tipo de descarga (D: Directa N:Normal)
            Dim Cond As String = "" ' Condición del contenedor (HH, HP, PP, PH, EM)
            Dim OpeLog As String = txtOperadorLogis.Text.Trim  ' Código Operador logístico
            Dim CUSU As String = sUsuario ' usuario logueado - falta
            Dim TfcfInt As Double = 0 'Total Flete collect Interno
            Dim TfctInt As Double = 0 ' Total THC Interno
            Dim Ptod As String = txtPtoDesc.Text.Trim  ' Código de Puerto de descarga

            objBLImpoBE = New BillOfLadingImpoBE
            objBLImpoBE.Tipo = sTipo
            objBLImpoBE.KVJE = KVJE
            objBLImpoBE.KBLM = KBLM
            objBLImpoBE.TOPE = TOPE
            objBLImpoBE.Nume = Nume
            objBLImpoBE.Tibl = Tibl
            objBLImpoBE.Lemi = Lemi
            objBLImpoBE.Femi = Femi
            objBLImpoBE.Emba = Emba
            objBLImpoBE.Csne = Csne
            objBLImpoBE.Noti = Noti
            objBLImpoBE.Not2 = Not2
            objBLImpoBE.Fwdr = Fwdr
            objBLImpoBE.Agad = Agad
            objBLImpoBE.Line = Line
            objBLImpoBE.Ptoo = Ptoo
            objBLImpoBE.Ptoe = Ptoe
            objBLImpoBE.Dfin = Dfin
            objBLImpoBE.Dfi2 = Dfi2
            objBLImpoBE.Dpte = Dpte
            objBLImpoBE.Dpto = Dpto
            objBLImpoBE.Dptd = Dptd
            objBLImpoBE.Ddfi = Ddfi
            objBLImpoBE.Ddf2 = Ddf2
            objBLImpoBE.Fomt = Fomt
            objBLImpoBE.OBSE = OBSE
            objBLImpoBE.Tfpf = Tfpf
            objBLImpoBE.Tfpt = Tfpt
            objBLImpoBE.Tfcf = Tfcf
            objBLImpoBE.Tfct = Tfct
            objBLImpoBE.CFLE = CFLE
            objBLImpoBE.Unid = Unid
            objBLImpoBE.Csue = Csue
            objBLImpoBE.Pkgs = Pkgs
            objBLImpoBE.Tafle = Tafle
            objBLImpoBE.Tathc = Tathc
            objBLImpoBE.ESTA = ESTA
            objBLImpoBE.Agge = Agge
            objBLImpoBE.Serv = Serv
            objBLImpoBE.Norig = Norig
            objBLImpoBE.Dtot = Dtot
            objBLImpoBE.Lpfp = Lpfp
            objBLImpoBE.Lpfc = Lpfc
            objBLImpoBE.Talm = Talm
            objBLImpoBE.Agdo = Agdo
            objBLImpoBE.Tdes = Tdes
            objBLImpoBE.Cond = Cond
            objBLImpoBE.OpeLog = OpeLog
            objBLImpoBE.CUSU = CUSU
            objBLImpoBE.TfcfInt = TfcfInt
            objBLImpoBE.TfctInt = TfctInt
            objBLImpoBE.Ptod = Ptod

            '--------------------------------------------------------------
            objBLImpoBC = New BillOfLadingImpoBC
            objBLImpoBC.ModificarBLimportacionCab(objBLImpoBE, bExito, sMensaje)

            If bExito = False Then
                Alerta("Error: Hubieron problemas al modificar el servicio.", False, String.Empty)
                Exit Sub
            Else
                ModificarMercaderia()
            End If

        Catch ex As Exception

        End Try

    End Sub

    Public Sub ModificarMercaderia()

        Try

        Catch ex As Exception

        End Try

    End Sub



    Public Sub LimpiarControles()


    End Sub


#Region "Modificar BL "

    Public Sub CargarDatosBlImpo()


        Try
            Dim objBL As List(Of BillOfLadingImpoBE)
            Dim objBLImpoBE As New BillOfLadingImpoBE
            Dim objBLImpoBC As New BillOfLadingImpoBC
            Dim bExito As Boolean = False
            Dim sMensaje As String = String.Empty

            objBLImpoBE.KBLM = Session("CodigBL")
            objBLImpoBE.KVJE = Session("CodigVje")

            objBL = objBLImpoBC.ObtieneBlImpoCabecera(objBLImpoBE, bExito, sMensaje)

            If bExito Then
                txtCodNave.Text = objBL.Item(0).KVJE
                txtDesNave.Text = objBL.Item(0).desKVJE
                txtBL.Text = objBL.Item(0).Nume
                cboUnidadPeso.SelectedValue = objBL.Item(0).Tibl
                txtFechaEmision.Text = objBL.Item(0).Femi
                txtLugarEmision.Text = objBL.Item(0).Lemi
                txtNumeroOrigen.Text = objBL.Item(0).Norig
                cboFull.SelectedValue = objBL.Item(0).Fomt
                cboAgenteAduana.SelectedValue = objBL.Item(0).Agge
                cboDocumentario.SelectedValue = objBL.Item(0).Agdo
                cboLinea.SelectedValue = objBL.Item(0).Line
                cboServ.SelectedValue = objBL.Item(0).Serv
                txtPtoOrigen.Text = objBL.Item(0).Ptoo
                txtDesPtoOrigen.Text = objBL.Item(0).Dpto
                txtPtoEmb.Text = objBL.Item(0).Ptoe
                txtDesPtoEmb.Text = objBL.Item(0).Dpte
                txtPtoDesc.Text = objBL.Item(0).Ptod
                txtDesPtoDesc.Text = objBL.Item(0).Dptd
                txtPtoFinal.Text = objBL.Item(0).Dfin
                txtDesDestinoFinal.Text = objBL.Item(0).Ddfi
                txtAgenteAduana.Text = objBL.Item(0).Agad
                txtOperadorLogis.Text = objBL.Item(0).OpeLog
                txtCodEmbarcador.Text = objBL.Item(0).Emba
                txtDesEmbarcador.Text = objBL.Item(0).desc_cod_emb
                txtObsEmbarcador.Text = objBL.Item(0).Ent_ObsEmb 'falta
                txtCodConsig.Text = objBL.Item(0).Csne
                txtDesConsig.Text = objBL.Item(0).desc_cod_cons
                txtObsConsig.Text = objBL.Item(0).Ent_ObsCons 'falta
                txtCodNotificante.Text = objBL.Item(0).Noti
                txtDesNotificante.Text = objBL.Item(0).desc_cod_not
                txtObsNotificante.Text = objBL.Item(0).Ent_ObsDoc 'falta

                CargarCabeceraMercaderia()

            End If

        Catch ex As Exception
            ex.Message.ToString()
        End Try

    End Sub

    Public Sub CargarCabeceraMercaderia()


        Try
            Dim objBL As List(Of BillOfLadingImpoBE)
            Dim objBLImpoBE As New BillOfLadingImpoBE
            Dim objBLImpoBC As New BillOfLadingImpoBC
            Dim bExito As Boolean = False
            Dim sMensaje As String = String.Empty

            objBLImpoBE.KBLM = Session("CodigBL")
            objBLImpoBE.KVJE = Session("CodigVje")

            objBL = objBLImpoBC.ObtieneBlImpoMercaderia(objBLImpoBE, bExito, sMensaje)

            If bExito Then
                cboProducto.Text = objBL.Item(0).Bem_Prod
                cboTipoBulto.SelectedValue = objBL.Item(0).Bem_TipoBulto
                txtCantMercaderia.Text = objBL.Item(0).Bem_Cant
                txtPartida.Text = objBL.Item(0).Bem_ParAran
                txtPesoBrutoMer.Text = objBL.Item(0).Bem_PesoBruto
                txtTotalMer.Text = objBL.Item(0).Bem_Total
                txtVolumen.Text = objBL.Item(0).Bem_Volumen
                txtMarcas.Text = objBL.Item(0).Bem_MarcaNum

                CargarDetalleMercaderia()

            End If
        Catch ex As Exception
            ex.Message.ToString()
        End Try


    End Sub

    Public Sub CargarDetalleMercaderia()


        Try

            Dim dtDetalle As New DataTable
            Dim dt As DataTable = Nothing
            Dim i As Integer
            Dim bExito As Boolean = False
            Dim sMensaje As String = String.Empty
            Dim objBLImpoBE As New BillOfLadingImpoBE

            objBLImpoBE.KBLM = Session("CodigBL")
            objBLImpoBE.KVJE = Session("CodigVje")

            Dim objBLImpoBC As New BillOfLadingImpoBC
            objBLImpoBC.ObtieneBlImpoMercaderiaDet(objBLImpoBE, dtDetalle, bExito, sMensaje)
            dgMercaderia.DataSource = dtDetalle
            dgMercaderia.DataBind()


            If dtDetalle.Rows.Count > 0 Then

                dt = Session("tbTempMercaderia")

                Do While i < dtDetalle.Rows.Count

                    Dim dRow As DataRow = dt.NewRow

                    dRow("IDMercaderia") = dtDetalle.Rows(i).Item(0).ToString
                    dRow("DescMercaderia") = dtDetalle.Rows(i).Item(1).ToString
                    dRow("dMercaderiaEstado") = dtDetalle.Rows(i).Item(2).ToString

                    dt.Rows.Add(dRow)
                    Session("tbTempMercaderia") = dt
                    i = i + 1
                Loop

                CargarDetalleFlete()

            End If
        Catch ex As Exception
            ex.Message.ToString()
        End Try

    End Sub


    Public Sub CargarDetalleFlete()


        Try
            Dim dtDetalle As New DataTable
            Dim dt As DataTable
            Dim i As Integer
            Dim bExito As Boolean = False
            Dim sMensaje As String = String.Empty
            Dim objBLImpoBE As New BillOfLadingImpoBE

            objBLImpoBE.KBLM = Session("CodigBL")
            objBLImpoBE.KVJE = Session("CodigVje")

            Dim objBLImpoBC As New BillOfLadingImpoBC
            objBLImpoBC.ObtieneBlImpoFlete(objBLImpoBE, dtDetalle, bExito, sMensaje)
            dgFlete.DataSource = dtDetalle
            dgFlete.DataBind()

            If dtDetalle.Rows.Count > 0 Then

                dt = Session("tbTempFlete")

                Do While i < dtDetalle.Rows.Count

                    Dim dRow As DataRow = dt.NewRow

                    dRow("dFleteID") = dtDetalle.Rows(i).Item(0).ToString
                    dRow("dFleteTarifa") = dtDetalle.Rows(i).Item(1).ToString
                    dRow("dFleteDesTarifa") = dtDetalle.Rows(i).Item(2).ToString
                    dRow("sFleteUnidad") = dtDetalle.Rows(i).Item(3).ToString
                    dRow("iFleteCantidad") = dtDetalle.Rows(i).Item(4).ToString
                    dRow("dFleteMontoTarifa") = dtDetalle.Rows(i).Item(5).ToString
                    dRow("dFletePC") = dtDetalle.Rows(i).Item(6).ToString
                    dRow("dFleteTotal") = dtDetalle.Rows(i).Item(7).ToString
                    dRow("sFleteMoneda") = dtDetalle.Rows(i).Item(8).ToString
                    dRow("sFleteLugarPago") = dtDetalle.Rows(i).Item(9).ToString
                    dRow("dFleteEstado") = dtDetalle.Rows(i).Item(10).ToString

                    dt.Rows.Add(dRow)
                    Session("tbTempFlete") = dt
                    i = i + 1
                Loop

                CargarDetalleContenedor()

            End If
        Catch ex As Exception
            ex.Message.ToString()
        End Try

    End Sub

    Public Sub CargarDetalleContenedor()

        Try
            Dim dtDetalle As New DataTable
            Dim dt As DataTable
            Dim i As Integer
            Dim bExito As Boolean = False
            Dim sMensaje As String = String.Empty
            Dim objBLImpoBE As New BillOfLadingImpoBE

            objBLImpoBE.KBLM = Session("CodigBL")
            objBLImpoBE.KVJE = Session("CodigVje")

            Dim objBLImpoBC As New BillOfLadingImpoBC
            objBLImpoBC.ObtieneBlImpoContenedor(objBLImpoBE, dtDetalle, bExito, sMensaje)
            dgContenedor.DataSource = dtDetalle
            dgContenedor.DataBind()



            If dtDetalle.Rows.Count > 0 Then

                dt = Session("tbTempContenedor")

                Do While i < dtDetalle.Rows.Count

                    Dim dRow As DataRow = dt.NewRow

                    dRow("sIDContenedor") = dtDetalle.Rows(i).Item(0).ToString
                    dRow("sPrefijo") = dtDetalle.Rows(i).Item(1).ToString
                    dRow("sNumero") = dtDetalle.Rows(i).Item(2).ToString
                    dRow("sTipo") = dtDetalle.Rows(i).Item(3).ToString
                    dRow("iPies") = dtDetalle.Rows(i).Item(4).ToString
                    dRow("sLineaInicial") = dtDetalle.Rows(i).Item(5).ToString
                    dRow("sLineaStock") = dtDetalle.Rows(i).Item(6).ToString
                    dRow("sCondicion") = dtDetalle.Rows(i).Item(7).ToString
                    dRow("sTipoPaquete") = dtDetalle.Rows(i).Item(8).ToString
                    dRow("iCantidad") = dtDetalle.Rows(i).Item(9).ToString
                    dRow("sUnidadMedida") = dtDetalle.Rows(i).Item(10).ToString
                    dRow("dPesoBrutoCont") = dtDetalle.Rows(i).Item(11).ToString
                    dRow("dPesoNeto") = dtDetalle.Rows(i).Item(12).ToString
                    dRow("sTara") = dtDetalle.Rows(i).Item(13).ToString
                    dRow("sVolumenContenedor") = dtDetalle.Rows(i).Item(14).ToString
                    dRow("sTemp") = dtDetalle.Rows(i).Item(15).ToString
                    dRow("sUNNO") = dtDetalle.Rows(i).Item(16).ToString
                    dRow("sCarrier") = dtDetalle.Rows(i).Item(17).ToString
                    dRow("sShipper") = dtDetalle.Rows(i).Item(18).ToString
                    dRow("sObservaciones") = dtDetalle.Rows(i).Item(19).ToString
                    dRow("sEstadoTrans") = dtDetalle.Rows(i).Item(20).ToString
                    dRow("dContenedorEstado") = dtDetalle.Rows(i).Item(21).ToString

                    dt.Rows.Add(dRow)
                    Session("tbTempContenedor") = dt
                    i = i + 1
                Loop

            End If


            CalcularTotales() '---

        Catch ex As Exception
            ex.Message.ToString()
        End Try

    End Sub

#End Region

#Region "Combos"

    Public Sub CargarTipoBultoMercaderia(ByVal sTipo As String)


        Dim listGeneralBE As List(Of GeneralBE) = New List(Of GeneralBE)
        Dim objGeneralBC As GeneralBC = New GeneralBC()

        Dim objUnidadSeleccione As GeneralBE = New GeneralBE
        objUnidadSeleccione.Codigo = 0
        objUnidadSeleccione.Descripcion = "[Seleccione]"
        listGeneralBE.Add(objUnidadSeleccione)
        objUnidadSeleccione.Codigo = sTipo

        listGeneralBE.AddRange(objGeneralBC.ListadoGeneral(objUnidadSeleccione))

        cboTipoBulto.DataSource = listGeneralBE
        cboTipoBulto.DataValueField = "Codigo"
        cboTipoBulto.DataTextField = "Descripcion"
        cboTipoBulto.DataBind()

    End Sub

    Public Sub CargarTipoBulto(ByVal sTipo As String)


        Dim listGeneralBE As List(Of GeneralBE) = New List(Of GeneralBE)
        Dim objGeneralBC As GeneralBC = New GeneralBC()

        Dim objUnidadSeleccione As GeneralBE = New GeneralBE
        objUnidadSeleccione.Codigo = 0
        objUnidadSeleccione.Descripcion = "[Seleccione]"
        listGeneralBE.Add(objUnidadSeleccione)
        objUnidadSeleccione.Codigo = sTipo

        listGeneralBE.AddRange(objGeneralBC.ListadoGeneral(objUnidadSeleccione))

        cboUnidadPeso.DataSource = listGeneralBE
        cboUnidadPeso.DataValueField = "Codigo"
        cboUnidadPeso.DataTextField = "Descripcion"
        cboUnidadPeso.DataBind()

    End Sub

    Public Sub CargarAgenteAduana(ByVal sTipo As String)


        Dim listGeneralBE As List(Of GeneralBE) = New List(Of GeneralBE)
        Dim objGeneralBC As GeneralBC = New GeneralBC()

        Dim objUnidadSeleccione As GeneralBE = New GeneralBE
        objUnidadSeleccione.Codigo = 0
        objUnidadSeleccione.Descripcion = "[Seleccione]"
        listGeneralBE.Add(objUnidadSeleccione)
        objUnidadSeleccione.Codigo = sTipo

        listGeneralBE.AddRange(objGeneralBC.ListadoGeneral(objUnidadSeleccione))

        cboAgenteAduana.DataSource = listGeneralBE
        cboAgenteAduana.DataValueField = "Codigo"
        cboAgenteAduana.DataTextField = "Descripcion"
        cboAgenteAduana.DataBind()

    End Sub

    Public Sub CargarAgenteDocumetario(ByVal sTipo As String)


        Dim listGeneralBE As List(Of GeneralBE) = New List(Of GeneralBE)
        Dim objGeneralBC As GeneralBC = New GeneralBC()

        Dim objUnidadSeleccione As GeneralBE = New GeneralBE
        objUnidadSeleccione.Codigo = 0
        objUnidadSeleccione.Descripcion = "[Seleccione]"
        listGeneralBE.Add(objUnidadSeleccione)
        objUnidadSeleccione.Codigo = sTipo

        listGeneralBE.AddRange(objGeneralBC.ListadoGeneral(objUnidadSeleccione))

        cboDocumentario.DataSource = listGeneralBE
        cboDocumentario.DataValueField = "Codigo"
        cboDocumentario.DataTextField = "Descripcion"
        cboDocumentario.DataBind()

    End Sub

    Public Sub CargarLinea()


        Dim listLineaBE As List(Of LineaBE) = New List(Of LineaBE)
        Dim objLineBC As LineaBC = New LineaBC()

        Dim objUnidadSeleccione As LineaBE = New LineaBE
        objUnidadSeleccione.Codigo = ""
        objUnidadSeleccione.Descripcion = ""
        listLineaBE.Add(objUnidadSeleccione)


        listLineaBE.AddRange(objLineBC.ListadoLinea(objUnidadSeleccione))

        objUnidadSeleccione.Descripcion = "[Seleccione]"
        cboLinea.DataSource = listLineaBE
        cboLinea.DataValueField = "Codigo"
        cboLinea.DataTextField = "Descripcion"
        cboLinea.DataBind()

    End Sub


    Public Sub CargarServicio(ByVal sTipo As String)


        Dim listGeneralBE As List(Of GeneralBE) = New List(Of GeneralBE)
        Dim objGeneralBC As GeneralBC = New GeneralBC()

        Dim objUnidadSeleccione As GeneralBE = New GeneralBE
        objUnidadSeleccione.Codigo = 0
        objUnidadSeleccione.Descripcion = "[Seleccione]"
        listGeneralBE.Add(objUnidadSeleccione)
        objUnidadSeleccione.Codigo = sTipo

        listGeneralBE.AddRange(objGeneralBC.ListadoGeneral(objUnidadSeleccione))

        cboServ.DataSource = listGeneralBE
        cboServ.DataValueField = "Codigo"
        cboServ.DataTextField = "Descripcion"
        cboServ.DataBind()

    End Sub


#End Region

#Region "Tab: Contenedor"

    Public Sub CrearTablaTemporalContenedor()

        Dim dt As New DataTable
        dt.Columns.Add("sIDContenedor")
        dt.Columns.Add("sPrefijo")
        dt.Columns.Add("sNumero")
        dt.Columns.Add("sTipo")
        dt.Columns.Add("iPies")
        dt.Columns.Add("sLineaInicial")
        dt.Columns.Add("sLineaStock")
        dt.Columns.Add("sCondicion")
        dt.Columns.Add("sTipoPaquete")
        dt.Columns.Add("iCantidad")
        dt.Columns.Add("sUnidadMedida")
        dt.Columns.Add("dPesoBrutoCont")
        dt.Columns.Add("dPesoNeto")
        dt.Columns.Add("sTara")
        dt.Columns.Add("sVolumenContenedor")
        dt.Columns.Add("sTemp")
        dt.Columns.Add("sUNNO")
        dt.Columns.Add("sCarrier")
        dt.Columns.Add("sShipper")
        dt.Columns.Add("sObservaciones")
        dt.Columns.Add("sEstadoTrans")
        dt.Columns.Add("dContenedorEstado")
        Session("tbTempContenedor") = dt

    End Sub


    Private Sub dgContenedor_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles dgContenedor.RowCommand

        Dim intCodigo As String = e.CommandArgument

        Select Case e.CommandName

            Case "Eliminar"

                If Session("TipoTransaccionBLImpo") = 1 Then ' Modificar
                    Eliminar_OpcionModificarContenedor(intCodigo)
                Else
                    Eliminar_OpcionNuevoContenedor(intCodigo)
                End If

                'Case "Editar"

                '    Dim dt As New DataTable
                '    Dim dtSel As New DataTable
                '    dt = Session("tbTempFlete")
                '    dtSel = SelectDataTable(dt, "dFleteID = " & intCodigo, "dFleteID DESC")
                '    ActivarControles(False)
                '    btnCancelar.Visible = True

                '    Me.txtIDFlete.Text = dtSel.Rows(0).Item("dFleteID").ToString
                '    Me.txtTarifaFlete.Text = dtSel.Rows(0).Item("dFleteTarifa").ToString
                '    Me.txtDesTarifaFlete.Text = dtSel.Rows(0).Item("dFleteDesTarifa").ToString
                '    Me.cboUnidadMedida.SelectedValue = dtSel.Rows(0).Item("sFleteUnidad").ToString
                '    Me.txtCant.Text = dtSel.Rows(0).Item("iFleteCantidad").ToString
                '    Me.txtMonto.Text = dtSel.Rows(0).Item("dFleteMontoTarifa").ToString
                '    Me.cboPC.SelectedValue = dtSel.Rows(0).Item("dFletePC").ToString
                '    'Me.txtTotalFlete.Text = dtSel.Rows(0).Item("dFleteTotal").ToString
                '    Me.cboMoneda.SelectedValue = dtSel.Rows(0).Item("sFleteMoneda").ToString
                '    Me.txtLugarDePago.Text = dtSel.Rows(0).Item("sFleteLugarPago").ToString

                '    Session("ActivarModificacion") = 1


        End Select


    End Sub


    Private Sub Eliminar_OpcionModificarContenedor(ByVal intCodigo As String)


        Dim i As Integer = 0
        Dim rwEliminar As String
        Dim dt As New DataTable
        dt = Session("tbTempContenedor")

        If dt.Rows.Count > 0 Then

            Do While i < dt.Rows.Count
                rwEliminar = dt.Rows(i).Item("sPrefijo").ToString

                If rwEliminar = CType(intCodigo, String) Then

                    If dt.Rows(i).Item("dContenedorEstado") = "0" Then ' si es nuevo se elimina definitivamnete
                        Me.dgContenedor.Rows(i).Visible = False
                        dt.Rows.Remove(dt.Rows(i))
                        Me.dgContenedor.DataSource = SelectDataTable(dt, "dContenedorEstado <> 'E'", "")
                        Me.dgContenedor.DataBind()
                    Else
                        dt.Rows(i).Item("dContenedorEstado") = "E" 'Eliminacion 
                        Me.dgContenedor.Rows(i).Visible = False
                        Me.dgContenedor.DataSource = SelectDataTable(dt, "dContenedorEstado <> 'E'", "")
                        Me.dgContenedor.DataBind()
                    End If

                End If

                i = i + 1
            Loop

            CalcularTotales()


        End If

    End Sub

    Private Sub Eliminar_OpcionNuevoContenedor(ByVal intCodigo As String)

        Dim i As Integer = 0
        Dim rwEliminar As String
        Dim dt As New DataTable
        dt = Session("tbTempContenedor")

        If dt.Rows.Count > 0 Then

            Do While i < dt.Rows.Count
                rwEliminar = dt.Rows(i).Item("sPrefijo").ToString ' dt.Rows(i).Item("sIDContenedor").ToString

                If rwEliminar = CType(intCodigo, String) Then
                    dgFlete.Rows(i).Visible = False
                    dt.Rows.Remove(dt.Rows(i))
                End If

                i = i + 1
            Loop

        End If

        dgContenedor.DataSource = dt
        dgContenedor.DataBind()

    End Sub


    Protected Sub btnAgregarCont_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAgregarCont.Click

        Try
            Dim drItem As DataRow
            Dim i As Integer = 0
            Dim dt As New DataTable
            Dim iValidacion As Integer = 0

            dt = Session("tbTempContenedor")

            '-------------------------------------------------------------------------------------
            'agrega datos a tabla temporal 
            '------------------------------------------------------------------------
            If dt.Rows.Count > 0 Then

                'Para validar si hay registros repetidos
                Do While i < dt.Rows.Count
                    drItem = dt.Rows(i)

                    If (txtConPrefijo.Text = drItem.Item(1).ToString) Then
                        If Session("TipoTransaccionBLImpo") = 1 Then ' Modificar
                            If Not dt.Rows(i).Item("dContenedorEstado") = "E" Then
                                iValidacion = iValidacion + 1
                            End If
                        Else
                            iValidacion = iValidacion + 1
                        End If
                    End If
                    i = i + 1
                Loop

                '--------------------------------------------------------------------------------------------------------------

                'If Session("ActivarModificacionContenedor") = 1 Then
                '    ActualizarTarifa()
                '    Exit Sub
                'End If

                If iValidacion = 0 Then
                    Dim dRow As DataRow = dt.NewRow
                    dRow("sIDContenedor") = Date.Now.Day & Date.Now.Hour & Date.Now.Minute & Date.Now.Second
                    dRow("sPrefijo") = Me.txtConPrefijo.Text
                    dRow("sNumero") = Me.txtContNumero.Text
                    dRow("sTipo") = Me.cboConTipo.SelectedValue
                    dRow("iPies") = Me.cboConPies.SelectedValue
                    dRow("sLineaInicial") = Me.cboConLineaInicial.SelectedValue
                    dRow("sLineaStock") = Me.cboConLineaStock.SelectedValue
                    dRow("sCondicion") = Me.cboConCondicion.SelectedValue
                    dRow("sTipoPaquete") = Me.cboConTipoPaquete.SelectedValue
                    dRow("iCantidad") = Me.txtConCantidad.Text
                    dRow("dPesoBrutoCont") = Me.txtConPesoBruto.Text
                    dRow("dPesoNeto") = Me.txtConPesoNeto.Text
                    dRow("sTara") = Me.txtConTara.Text
                    dRow("sVolumenContenedor") = Me.txtConVolumen.Text
                    dRow("sTemp") = Me.txtConTemperatura.Text
                    dRow("sUNNO") = Me.txtConUNNO.Text
                    dRow("sCarrier") = Me.txtConCarrier.Text
                    dRow("sShipper") = Me.txtConShiper.Text
                    dRow("sObservaciones") = Me.txtConObservacion.Text
                    dRow("sEstadoTrans") = Me.cboConEstadoTransf.SelectedValue
                    dRow("sUnidadMedida") = Me.cboUnidadPeso.SelectedValue


                    If Session("TipoTransaccionBLImpo") = 1 Then ' Modificar
                        dRow("dContenedorEstado") = "0" 'Registro por modificar
                    Else
                        dRow("dContenedorEstado") = "0" 'Registro Nuevo
                    End If

                    dt.Rows.Add(dRow)
                    Session("tbTempContenedor") = dt
                    Me.dgContenedor.DataSource = SelectDataTable(dt, "dContenedorEstado <> 'E'", "")
                    Me.dgContenedor.DataBind()

                    CalcularTotales() '---

                    Exit Sub
                Else
                    MsgBox("ERROR: Ya se ingreso el mismo contenedor.", True, String.Empty)
                    Exit Sub
                End If

            Else
                Dim dRow As DataRow = dt.NewRow
                dRow("sIDContenedor") = Date.Now.Day & Date.Now.Hour & Date.Now.Minute & Date.Now.Second
                dRow("sPrefijo") = Me.txtConPrefijo.Text()
                dRow("sNumero") = Me.txtContNumero.Text
                dRow("sTipo") = Me.cboConTipo.SelectedValue
                dRow("iPies") = Me.cboConPies.SelectedValue
                dRow("sLineaInicial") = Me.cboConLineaInicial.SelectedValue
                dRow("sLineaStock") = Me.cboConLineaStock.SelectedValue
                dRow("sCondicion") = Me.cboConCondicion.SelectedValue
                dRow("sTipoPaquete") = Me.cboConTipoPaquete.SelectedValue
                dRow("iCantidad") = Me.txtConCantidad.Text
                dRow("dPesoBrutoCont") = Me.txtConPesoBruto.Text
                dRow("dPesoNeto") = Me.txtConPesoNeto.Text
                dRow("sTara") = Me.txtConTara.Text
                dRow("sVolumenContenedor") = Me.txtConVolumen.Text
                dRow("sTemp") = Me.txtConTemperatura.Text
                dRow("sUNNO") = Me.txtConUNNO.Text
                dRow("sCarrier") = Me.txtConCarrier.Text
                dRow("sShipper") = Me.txtConShiper.Text
                dRow("sObservaciones") = Me.txtConObservacion.Text
                dRow("sEstadoTrans") = Me.cboConEstadoTransf.SelectedValue
                dRow("sUnidadMedida") = Me.cboUnidadPeso.SelectedValue


                If Session("TipoTransaccionBLImpo") = 1 Then ' Modificar
                    dRow("dContenedorEstado") = "0" 'Registro por modificar
                Else
                    dRow("dContenedorEstado") = "0" 'Registro Nuevo
                End If


                dt.Rows.Add(dRow)
                Session("tbTempContenedor") = dt
                Me.dgContenedor.DataSource = SelectDataTable(dt, "dContenedorEstado <> 'E'", "")
                Me.dgContenedor.DataBind()

                CalcularTotales() '---

            End If


        Catch ex As Exception
            ex.Message.ToString()
        End Try


    End Sub



    Public Sub CalcularTotales()

        Dim drItem As DataRow
        Dim i As Integer = 0
        Dim dt As DataTable
        dt = Session("tbTempContenedor")
        Dim sTotalPesoBruto As Double
        Dim sTotalPesoNeto As Double
        Dim sTotalTara As Double
        Dim sTotalVolumen As Double

        dt = SelectDataTable(dt, "dContenedorEstado <> 'E'", "")

        Do While i < dt.Rows.Count
            drItem = dt.Rows(i)
            sTotalPesoBruto = sTotalPesoBruto + CType(dt.Rows(i).Item("dPesoBrutoCont"), Double)
            sTotalTara = sTotalTara + CType(dt.Rows(i).Item("sTara"), Double)
            sTotalPesoNeto = sTotalPesoNeto + CType(dt.Rows(i).Item("dPesoNeto"), Double)
            sTotalVolumen = sTotalVolumen + CType(dt.Rows(i).Item("sVolumenContenedor"), Double)
            i = i + 1
        Loop


        'Calcular camtidades 
        txtTotalPesoBruto.Text = sTotalPesoBruto
        txtTotalPesoNeto.Text = sTotalPesoNeto
        txtTotalPesoTara.Text = sTotalTara
        txtTotalVolumen.Text = sTotalVolumen
    End Sub



#End Region


#Region "Tab: Flete"

    Public Sub CrearTablaTemporalFlete()

        Dim dt As New DataTable
        dt.Columns.Add("dFleteID")
        dt.Columns.Add("dFleteTarifa")
        dt.Columns.Add("dFleteDesTarifa")
        dt.Columns.Add("sFleteUnidad")
        dt.Columns.Add("iFleteCantidad")
        dt.Columns.Add("dFleteMontoTarifa")
        dt.Columns.Add("dFletePC")
        dt.Columns.Add("dFleteTotal")
        dt.Columns.Add("sFleteMoneda")
        dt.Columns.Add("sFleteLugarPago")
        dt.Columns.Add("dFleteEstado")
        Session("tbTempFlete") = dt
        'dt.Columns.Add("Tarifa").DataType = System.Type.GetType("System.Object")
    End Sub



    Protected Sub btnAgregar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAgregar.Click

        Try
            Dim drItem As DataRow
            Dim i As Integer = 0
            Dim dt As New DataTable
            Dim iValidacion As Integer = 0

            dt = Session("tbTempFlete")

            '-------------------------------------------------------------------------------------
            If txtTarifaFlete.Text = String.Empty Then
                MsgBox("Ingrese la tarifa.", True, String.Empty)
                Exit Sub
            ElseIf cboUnidadMedida.SelectedItem.Text = "[Seleccione]" Then
                MsgBox("Seleccione la unidad de medida.", True, String.Empty)
                Exit Sub
            ElseIf txtCant.Text.Trim = "" Then
                MsgBox("Ingrese la cantidad.", True, String.Empty)
                Exit Sub
            ElseIf txtMonto.Text = "" Then
                MsgBox("Ingrese el monto.", True, String.Empty)
                Exit Sub
            ElseIf cboPC.SelectedItem.Text = "[Seleccione]" Then
                MsgBox("Seleccione el P/C.", True, String.Empty)
                Exit Sub
            ElseIf cboMoneda.SelectedItem.Text = "[Seleccione]" Then
                MsgBox("Seleccione la moneda.", True, String.Empty)
                Exit Sub
            ElseIf txtLugarDePago.Text = String.Empty Then
                MsgBox("Ingrese el lugar de pago.", True, String.Empty)
                Exit Sub
            End If


            '-------------------------------------------------------------------------------------
            'agrega datos a tabla temporal 
            '------------------------------------------------------------------------
            If dt.Rows.Count > 0 Then

                'Para validar si hay registros repetidos
                Do While i < dt.Rows.Count
                    drItem = dt.Rows(i)

                    If (txtTarifaFlete.Text = drItem.Item(1).ToString) Then
                        If Session("TipoTransaccionBLImpo") = 1 Then ' Modificar
                            If Not dt.Rows(i).Item("dFleteEstado") = "E" Then
                                iValidacion = iValidacion + 1
                            End If
                        Else
                            iValidacion = iValidacion + 1
                        End If
                    End If
                    i = i + 1
                Loop

                '--------------------------------------------------------------------------------------------------------------

                If Session("ActivarModificacion") = 1 Then ' SI SE MODIFICA
                    ActualizarTarifa()
                    Exit Sub
                End If

                If iValidacion = 0 Then
                    Dim dRow As DataRow = dt.NewRow
                    dRow("dFleteID") = Date.Now.Day & Date.Now.Hour & Date.Now.Minute & Date.Now.Second
                    dRow("dFleteTarifa") = Me.txtTarifaFlete.Text
                    dRow("dFleteDesTarifa") = Me.txtDesTarifaFlete.Text
                    dRow("sFleteUnidad") = Me.cboUnidadMedida.SelectedValue
                    dRow("iFleteCantidad") = Me.txtCant.Text
                    dRow("dFleteMontoTarifa") = Me.txtMonto.Text
                    dRow("dFletePC") = Me.cboPC.SelectedValue
                    dRow("dFleteTotal") = Val(txtCant.Text.Trim) * Val(txtMonto.Text)
                    dRow("sFleteMoneda") = Me.cboMoneda.SelectedValue
                    dRow("sFleteLugarPago") = Me.txtLugarDePago.Text

                    If Session("TipoTransaccionBLImpo") = 1 Then ' Modificar
                        dRow("dFleteEstado") = "0" 'Registro por modificar
                    Else
                        dRow("dFleteEstado") = "0" 'Registro Nuevo
                    End If

                    dt.Rows.Add(dRow)
                    Session("tbTempFlete") = dt
                    Me.dgFlete.DataSource = SelectDataTable(dt, "dFleteEstado <> 'E'", "")
                    Me.dgFlete.DataBind()
                    Exit Sub
                Else
                    MsgBox("ERROR: Ya se ingreso la misma tarifa.", True, String.Empty)
                    Exit Sub
                End If

            Else
                Dim dRow As DataRow = dt.NewRow
                dRow("dFleteID") = Date.Now.Day & Date.Now.Hour & Date.Now.Minute & Date.Now.Second
                dRow("dFleteTarifa") = Me.txtTarifaFlete.Text
                dRow("dFleteDesTarifa") = Me.txtDesTarifaFlete.Text
                dRow("sFleteUnidad") = Me.cboUnidadMedida.SelectedValue
                dRow("iFleteCantidad") = Me.txtCant.Text
                dRow("dFleteMontoTarifa") = Me.txtMonto.Text
                dRow("dFletePC") = Me.cboPC.SelectedValue
                dRow("dFleteTotal") = Val(txtCant.Text.Trim) * Val(txtMonto.Text)
                dRow("sFleteMoneda") = Me.cboMoneda.SelectedValue
                dRow("sFleteLugarPago") = Me.txtLugarDePago.Text

                If Session("TipoTransaccionBLImpo") = 1 Then ' Modificar
                    dRow("dFleteEstado") = "0" 'Registro por modificar
                Else
                    dRow("dFleteEstado") = "0" 'Registro Nuevo
                End If


                dt.Rows.Add(dRow)
                Session("tbTempFlete") = dt
                Me.dgFlete.DataSource = SelectDataTable(dt, "dFleteEstado <> 'E'", "")
                Me.dgFlete.DataBind()
            End If


        Catch ex As Exception
            ex.Message.ToString()
        End Try

    End Sub

    Function SelectDataTable(ByVal dt As DataTable, ByVal filter As String, ByVal sort As String) As DataTable

        Dim rows As DataRow()
        Dim dtNew As DataTable
        dtNew = dt.Clone()
        rows = dt.Select(filter, sort)
        For Each dr As DataRow In rows
            dtNew.ImportRow(dr)
        Next
        Return dtNew

    End Function

    Public Sub ActualizarTarifa()

        Try
            Dim i As Integer = 0
            Dim dt As New DataTable
            dt = Session("tbTempFlete")
            btnCancelar.Enabled = True

            If dt.Rows.Count > 0 Then

                Do While i < dt.Rows.Count

                    If dt.Rows(i).Item("dFleteID").ToString = CType(txtIDFlete.Text.Trim, String) Then
                        'dt.Rows(i).Item("Tarifa") = CType(txtTarifa.Text, Double)
                        dt.Rows(i).Item("dFleteTarifa") = Me.txtTarifaFlete.Text
                        dt.Rows(i).Item("dFleteDesTarifa") = Me.txtDesTarifaFlete.Text
                        dt.Rows(i).Item("sFleteUnidad") = Me.cboUnidadMedida.SelectedValue
                        dt.Rows(i).Item("iFleteCantidad") = Me.txtCant.Text
                        dt.Rows(i).Item("dFleteMontoTarifa") = Me.txtMonto.Text
                        dt.Rows(i).Item("dFletePC") = Me.cboPC.SelectedValue
                        dt.Rows(i).Item("dFleteTotal") = Val(dt.Rows(i).Item("iFleteCantidad")) * Val(dt.Rows(i).Item("dFleteMontoTarifa"))
                        dt.Rows(i).Item("sFleteMoneda") = Me.cboMoneda.SelectedValue
                        dt.Rows(i).Item("sFleteLugarPago") = Me.txtLugarDePago.Text
                        dt.Rows(i).Item("dFleteEstado") = "U"
                        dgFlete.DataSource = dt
                        dgFlete.DataBind()
                    End If
                    i = i + 1
                Loop
            End If

            Session("ActivarModificacion") = 0
            ActivarControles(True)
            btnCancelar.Visible = False
            LimpiarDatosFletes()

        Catch ex As Exception
            ex.Message.ToString()
        End Try

    End Sub

    Public Sub LimpiarDatosFletes()

        Me.txtIDFlete.Text = String.Empty
        Me.txtTarifaFlete.Text = String.Empty
        Me.txtDesTarifaFlete.Text = String.Empty
        Me.cboUnidadMedida.SelectedIndex = 0
        Me.txtCant.Text = String.Empty
        Me.txtMonto.Text = String.Empty
        Me.cboPC.SelectedIndex = 0
        Me.cboMoneda.SelectedIndex = 0
        Me.txtLugarDePago.Text = String.Empty


    End Sub

    Private Sub dgFlete_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles dgFlete.RowCommand

        Dim intCodigo As String = e.CommandArgument

        Select Case e.CommandName

            Case "Eliminar"

                If Session("TipoTransaccionBLImpo") = 1 Then ' Modificar
                    Eliminar_OpcionModificar(intCodigo)
                Else
                    Eliminar_OpcionNuevo(intCodigo)
                End If

            Case "Editar"

                Dim dt As New DataTable
                Dim dtSel As New DataTable
                dt = Session("tbTempFlete")
                dtSel = SelectDataTable(dt, "dFleteID = " & intCodigo, "dFleteID DESC")
                ActivarControles(False)
                btnCancelar.Visible = True

                Me.txtIDFlete.Text = dtSel.Rows(0).Item("dFleteID").ToString
                Me.txtTarifaFlete.Text = dtSel.Rows(0).Item("dFleteTarifa").ToString
                Me.txtDesTarifaFlete.Text = dtSel.Rows(0).Item("dFleteDesTarifa").ToString
                Me.cboUnidadMedida.SelectedValue = dtSel.Rows(0).Item("sFleteUnidad").ToString
                Me.txtCant.Text = dtSel.Rows(0).Item("iFleteCantidad").ToString
                Me.txtMonto.Text = dtSel.Rows(0).Item("dFleteMontoTarifa").ToString
                Me.cboPC.SelectedValue = dtSel.Rows(0).Item("dFletePC").ToString
                'Me.txtTotalFlete.Text = dtSel.Rows(0).Item("dFleteTotal").ToString
                Me.cboMoneda.SelectedValue = dtSel.Rows(0).Item("sFleteMoneda").ToString
                Me.txtLugarDePago.Text = dtSel.Rows(0).Item("sFleteLugarPago").ToString

                Session("ActivarModificacion") = 1


        End Select

    End Sub

    Private Sub Eliminar_OpcionModificar(ByVal intCodigo As String)


        Dim i As Integer = 0
        Dim rwEliminar As String
        Dim dt As New DataTable
        dt = Session("tbTempFlete")

        If dt.Rows.Count > 0 Then

            Do While i < dt.Rows.Count
                rwEliminar = dt.Rows(i).Item("dFleteID").ToString

                If rwEliminar = CType(intCodigo, String) Then

                    If dt.Rows(i).Item("dFleteEstado") = "0" Then ' si es nuevo se elimina definitivamnete
                        Me.dgFlete.Rows(i).Visible = False
                        dt.Rows.Remove(dt.Rows(i))
                        Me.dgFlete.DataSource = SelectDataTable(dt, "dFleteEstado <> 'E'", "")
                        Me.dgFlete.DataBind()
                    Else
                        dt.Rows(i).Item("dFleteEstado") = "E" 'Eliminacion 
                        Me.dgFlete.Rows(i).Visible = False
                        Me.dgFlete.DataSource = SelectDataTable(dt, "dFleteEstado <> 'E'", "")
                        Me.dgFlete.DataBind()
                    End If

                End If

                i = i + 1
            Loop

        End If

    End Sub

    Private Sub Eliminar_OpcionNuevo(ByVal intCodigo As String)

        Dim i As Integer = 0
        Dim rwEliminar As String
        Dim dt As New DataTable
        dt = Session("tbTempFlete")

        If dt.Rows.Count > 0 Then

            Do While i < dt.Rows.Count
                rwEliminar = dt.Rows(i).Item("dFleteID").ToString

                If rwEliminar = CType(intCodigo, String) Then
                    dgFlete.Rows(i).Visible = False
                    dt.Rows.Remove(dt.Rows(i))
                End If

                i = i + 1
            Loop

        End If

        dgFlete.DataSource = dt
        dgFlete.DataBind()

    End Sub

    Public Sub ActivarControles(ByVal Tipo As Boolean)
        'cboPais.Enabled = Tipo
        'cboCiudad.Enabled = Tipo
        ''txtCodProveedor.Enabled = Tipo
        ''txtRazonSocial.Enabled = Tipo
        'cboTarifa.Enabled = Tipo
    End Sub

    Protected Sub btnLimpiar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnLimpiar.Click
        LimpiarDatosFletes()
    End Sub

    Protected Sub btnCancelar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCancelar.Click
        ActivarControles(True)
        LimpiarDatosFletes()
        btnCancelar.Visible = False

        Session("ActivarModificacion") = 0

    End Sub



#End Region



    Public Sub CrearTablaMercaderia()

        Dim dt As New DataTable
        dt.Columns.Add("IDMercaderia")
        dt.Columns.Add("DescMercaderia")
        dt.Columns.Add("dMercaderiaEstado")
        Session("tbTempMercaderia") = dt

    End Sub


    Protected Sub btnAgregarMercaderia_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAgregarMercaderia.Click

        Try

            Dim drItem As DataRow
            Dim i As Integer = 0
            Dim dt As New DataTable
            Dim iValidacion As Integer = 0

            dt = Session("tbTempMercaderia")

            '-------------------------------------------------------------------------------------
            If txtMercaderia.Text = String.Empty Then
                MsgBox("Ingrese la tarifa.", True, String.Empty)
                Exit Sub
            End If
            '-------------------------------------------------------------------------------------
            'agrega datos a tabla temporal 
            '------------------------------------------------------------------------
            If dt.Rows.Count > 0 Then

                'Para validar si hay registros repetidos
                Do While i < dt.Rows.Count
                    drItem = dt.Rows(i)

                    If (txtMercaderia.Text = drItem.Item(1).ToString) Then
                        If Session("TipoTransaccionBLImpo") = 1 Then ' Modificar
                            If Not dt.Rows(i).Item("dMercaderiaEstado") = "E" Then
                                iValidacion = iValidacion + 1
                            End If
                        Else
                            iValidacion = iValidacion + 1
                        End If
                    End If
                    i = i + 1
                Loop

                '--------------------------------------------------------------------------------------------------------------


                If iValidacion = 0 Then
                    Dim dRow As DataRow = dt.NewRow
                    dRow("IDMercaderia") = Date.Now.Day & Date.Now.Hour & Date.Now.Minute & Date.Now.Second
                    dRow("DescMercaderia") = Me.txtMercaderia.Text

                    If Session("TipoTransaccionBLImpo") = 1 Then ' Modificar
                        dRow("dMercaderiaEstado") = "0" 'Registro por modificar
                    Else
                        dRow("dMercaderiaEstado") = "0" 'Registro Nuevo
                    End If

                    dt.Rows.Add(dRow)
                    Session("tbTempMercaderia") = dt
                    Me.dgMercaderia.DataSource = SelectDataTable(dt, "dMercaderiaEstado <> 'E'", "")
                    Me.dgMercaderia.DataBind()
                    Exit Sub
                Else
                    MsgBox("ERROR: Ya se ingreso la misma mercaderia.", True, String.Empty)
                    Exit Sub
                End If

            Else
                Dim dRow As DataRow = dt.NewRow
                dRow("IDMercaderia") = Date.Now.Day & Date.Now.Hour & Date.Now.Minute & Date.Now.Second
                dRow("DescMercaderia") = Me.txtMercaderia.Text

                If Session("TipoTransaccionBLImpo") = 1 Then ' Modificar
                    dRow("dMercaderiaEstado") = "0" 'Registro por modificar
                Else
                    dRow("dMercaderiaEstado") = "0" 'Registro Nuevo
                End If


                dt.Rows.Add(dRow)
                Session("tbTempMercaderia") = dt
                Me.dgMercaderia.DataSource = SelectDataTable(dt, "dMercaderiaEstado <> 'E'", "")
                Me.dgMercaderia.DataBind()
            End If


        Catch ex As Exception
            ex.Message.ToString()
        End Try


    End Sub



    Private Sub dgMercaderia_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles dgMercaderia.RowCommand
        Dim intCodigo As String = e.CommandArgument

        Select Case e.CommandName

            Case "Eliminar"

                If Session("TipoTransaccionBLImpo") = 1 Then ' Modificar
                    Eliminar_OpcionModificar_Mercaderia(intCodigo)
                Else
                    Eliminar_OpcionNuevo_Mercaderia(intCodigo)
                End If

        End Select
    End Sub


    Private Sub Eliminar_OpcionModificar_Mercaderia(ByVal intCodigo As String)


        Dim i As Integer = 0
        Dim rwEliminar As String
        Dim dt As New DataTable
        dt = Session("tbTempMercaderia")

        If dt.Rows.Count > 0 Then

            Do While i < dt.Rows.Count
                rwEliminar = dt.Rows(i).Item("IDMercaderia").ToString

                If rwEliminar = CType(intCodigo, String) Then

                    If dt.Rows(i).Item("dMercaderiaEstado") = "0" Then ' si es nuevo se elimina definitivamnete
                        Me.dgMercaderia.Rows(i).Visible = False
                        dt.Rows.Remove(dt.Rows(i))
                        Me.dgMercaderia.DataSource = SelectDataTable(dt, "dMercaderiaEstado <> 'E'", "")
                        Me.dgMercaderia.DataBind()
                    Else
                        dt.Rows(i).Item("dMercaderiaEstado") = "E" 'Eliminacion 
                        Me.dgMercaderia.Rows(i).Visible = False
                        Me.dgMercaderia.DataSource = SelectDataTable(dt, "dMercaderiaEstado <> 'E'", "")
                        Me.dgMercaderia.DataBind()
                    End If

                End If

                i = i + 1
            Loop

        End If

    End Sub

    Private Sub Eliminar_OpcionNuevo_Mercaderia(ByVal intCodigo As String)

        Dim i As Integer = 0
        Dim rwEliminar As String
        Dim dt As New DataTable
        dt = Session("tbTempMercaderia")

        If dt.Rows.Count > 0 Then

            Do While i < dt.Rows.Count
                rwEliminar = dt.Rows(i).Item("IDMercaderia").ToString

                If rwEliminar = CType(intCodigo, String) Then
                    dgMercaderia.Rows(i).Visible = False
                    dt.Rows.Remove(dt.Rows(i))
                End If

                i = i + 1
            Loop

        End If

        dgMercaderia.DataSource = dt
        dgMercaderia.DataBind()

    End Sub

    Protected Sub btnSalir_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSalir0.Click
        Response.Redirect("Consultar_BillOfLading_Expo.aspx")
    End Sub

    Protected Sub txtIDFlete_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles txtIDFlete.TextChanged

    End Sub

    Protected Sub btnLimpiarCont_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnLimpiarCont.Click
        txtConPrefijo.Text = ""
        txtContNumero.Text = ""
        txtConCantidad.Text = ""
        txtConPesoBruto.Text = ""
        txtConPesoNeto.Text = ""
        txtConTara.Text = ""
        txtConVolumen.Text = ""
        txtConTemperatura.Text = ""
        txtConUNNO.Text = ""
        txtConCarrier.Text = ""
        txtConShiper.Text = ""
        txtConObservacion.Text = ""
    End Sub

    Protected Sub sTab_ActiveTabChanged(source As Object, e As DevExpress.Web.ASPxTabControl.TabControlEventArgs) Handles sTab.ActiveTabChanged

    End Sub
End Class